﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;

namespace MyDLL
{
    /// <summary>
    /// 正则表达式类库
    /// </summary>
    public class Regex_Common
    {
        /// <summary>
        /// 输出正则表达式查询结果，并返回二维字符串数组
        /// </summary>
        /// <param name="regexStr">正则表达式</param>
        /// <param name="str0">原始字符串</param>
        /// <param name="indexArr">Result的下标，如：0或1</param>
        /// <returns>返回二维字符串数组；如果出错，则返回1*1的二维数组，且唯一的元素值为“无匹配结果”。</returns>
        public static string[,] MatchCollection_Results(string regexStr, string str0, int[] indexArr)
        {
            string[,] res;
            MatchCollection matchCollection = new Regex(regexStr).Matches(str0);
            int countMC = matchCollection.Count;
            int countIndex = indexArr.Length;
            if (countMC == 0)
            {
                res = new string[1,1];
                res[0, 0] = "无匹配结果";
                return res;
            }
            res = new string[countMC,countIndex];
            for (int i = 0; i < countMC; i++)
            {
                for (int j = 0; j < countIndex; j++)
                {
                    res[i,j] = matchCollection[i].Result("$" + indexArr[j]);
                }                
            }
            return res;
        }

        /// <summary>
        /// 输出正则表达式查询结果，并返回一维字符串数组
        /// </summary>
        /// <param name="regexStr">正则表达式</param>
        /// <param name="str0">原始字符串</param>
        /// <param name="index">Result的下标，如：0或1，默认为0。</param>
        /// <returns>返回二维字符串数组；如果出错，则返回1*1的二维数组，且唯一的元素值为“无匹配结果”。</returns>
        public static string[] MatchCollection_Results(string regexStr, string str0, int index = 0)
        {
            string[] res;
            MatchCollection matchCollection = new Regex(regexStr).Matches(str0);
            int countMC = matchCollection.Count;
            if (countMC == 0)
            {
                res = new string[1];
                res[0] = "无匹配结果";
                return res;
            }
            res = new string[countMC];
            for (int i = 0; i < countMC; i++)
            {
                res[i] = matchCollection[i].Result("$" + index.ToString());
            }
            return res;
        }

        /// <summary>
        /// 正则表达式字符串正常化，在字符串中的正则表达式特殊字符前加“\”。
        /// </summary>
        /// <param name="regexStr"></param>
        /// <returns></returns>
        public static string RegexStrNormalize(string regexStr)
        {
            string res = regexStr;
            foreach (char c in specialCharacters)
            {
                res = res.Replace(c.ToString(), @"\" + c);
            }
            return res;
        }

        /// <summary>
        /// 正则表达式中的特殊字符。详见：https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-escapes-in-regular-expressions#:~:text=The%20backslash%20%28%29%20in%20a%20regular%20expression%20indicates,represents%20a%20tab%2C%20and%20x020%20represents%20a%20space.
        /// </summary>
        public static string specialCharacters = @"\.$^{[(|)*+?";
        /// <summary>
        /// 将字符串中的英文双引号替换成中文双引号
        /// </summary>
        /// <param name="str0">待处理的字符串</param>
        /// <returns>返回新的字符串</returns>
        public static string ReplaceEnglishCommaWithChineseComma(string str0)
        {
            string[,] resArr;
            string res, tempStr;
            resArr = MatchCollection_Results("\"([\\s\\S]*?)\"", str0, new int[] { 0 });
            tempStr = resArr[0, 0].Replace("\"", "");
            res = str0.Replace(resArr[0, 0], "“" + tempStr + "”");
            return res;
        }

        /// <summary>
        /// 将字符串中多余的空格去除（非英文字母）。
        /// </summary>
        /// <param name="str0"></param>
        /// <returns></returns>
        public static string RemoveRedundantSpaces_NonEnglish(string str0)
        {
            string[,] resArr;
            string res;
            resArr = MatchCollection_Results("[^A-Za-z]( +)[^A-Za-z]", str0, new int[] { 1 });
            res = str0.Replace(resArr[0, 0], "");
            return res;
        }

        /// <summary>
        /// 将字符串中多余的空格去除（英文字母）。
        /// </summary>
        /// <param name="stro"></param>
        /// <returns></returns>
        public static string RemoveRedundantSpaces_English(string stro)
        {
            return Regex_Common.RegexReplace(stro, "( )+", " ");
        }
        /// <summary>
        /// 对MatchCollection_Results返回的二维数组进行处理
        /// </summary>
        /// <param name="inputArr">待处理二维数组</param>
        /// <returns></returns>
        public static string[,] MC_Results_Trim(string[,] inputArr)
        {
            int rowNum = inputArr.GetLength(0);
            int colNum = inputArr.GetLength(1);
            string[,] res = new string[rowNum, colNum];
            for (int i = 0; i < rowNum; i++)
            {
                for (int j = 0; j < colNum; j++)
                {
                    res[i, j] = StrTrimByVal(inputArr[i, j]);
                }
            }
            return res;
        }

        /// <summary>
        /// 用正则表达式对字符串进行替换操作。
        /// </summary>
        /// <param name="str0">待处理的字符串</param>
        /// <param name="regexStr">正则表达式</param>
        /// <param name="str_ReplaceWith">用来替换的字符串</param>
        /// <returns>返回处理后的字符串</returns>
        public static string RegexReplace(string str0, string regexStr, string str_ReplaceWith)
        {
            return new Regex(regexStr).Replace(str0, str_ReplaceWith);
        }

        /// <summary>
        /// 判断正则表达式是否匹配到结果。
        /// </summary>
        /// <param name="str0">待处理的字符串</param>
        /// <param name="regexStr">正则表达式</param>
        /// <returns>返回bool值。</returns>
        public static bool isMatch(string str0, string regexStr)
        {
            return new Regex(regexStr).IsMatch(str0);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="regexStr">正则表达式</param>
        /// <param name="str0">原始字符串</param>
        /// <param name="index">Result的下标，如：0或1，默认为0。</param>
        /// <param name="stopPattern">停止字符串，默认为"\n"</param>
        /// <returns></returns>
        public static string Match_StopOnFirstMatch(string regexStr, string str0, int index = 0, string stopPattern = "\n")
        {
            int endIndex = str0.IndexOf(stopPattern);
            if (endIndex == -1)
                return MatchCollection_Results(regexStr, str0, index)[0];

            endIndex = endIndex + stopPattern.Length;
            
            string subStr0 = str0.Substring(0, endIndex - 0);
            string res = MatchCollection_Results(regexStr, subStr0, index)[0];
            if (res != "无匹配结果")
                return res;
            else
                res = Match_StopOnFirstMatch(regexStr, str0.Substring(endIndex), index, stopPattern);
            return res;
        }

        /// <summary>
        /// 对单个字符串进行处理，适应csv文件规范。
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StrTrimByVal(string str)
        {
            if (str != null && str !="")
            {
                return str.Replace(",", "，").Replace("&#34;", "”").Replace("&#39;", ((char)39).ToString()).Trim(); ;
            }
            else
            {
                return str;
            }    
        }
        /// <summary>
        /// 对单个字符串进行处理（ref引用），适应csv文件规范。
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static void StrTrimByRef(ref string str)
        {
            if (str != null && str != "")
                str = str.Replace(",", "，").Replace("&#34;", "”").Replace("&#39;", ((char)39).ToString()).Trim(); ;
        }
    }
}
